import face_recognition
import numpy as np
from flask import Flask, jsonify, request, redirect

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def get_face_encodings(file_stream):
    # 载入用户上传的图片
    img = face_recognition.load_image_file(file_stream)
    # 为用户上传的图片中的人脸编码
    unknown_face_encodings = face_recognition.face_encodings(img)
    face_encodings=[]
    for encoding in unknown_face_encodings:
        face_encodings.append(encoding.tolist())
    # 讲识别结果以json键值对的数据结构输出
    face_found = False
    face_num = len(unknown_face_encodings)
    if face_num > 0:
        face_found=True
    result = {
        "face_found": face_found,
        "face_number": face_num,
        "face_encodings": face_encodings
    }
    return jsonify(result)


@app.route('/face_encodings', methods=['GET', 'POST'])
def get_face_encodings_url():
    # 检测图片是否上传成功
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)

        file = request.files['file']

        if file.filename == '':
            return redirect(request.url)

        if file and allowed_file(file.filename):
            # 图片上传成功，检测图片中的人脸
            return get_face_encodings(file)

    # 图片上传失败，输出以下html代码
    # 图片上传失败，输出以下html代码
    return '''
    <!doctype html>
    <title>人脸识别</title>
    <h1>人脸图片上传</h1>
    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="上传">
    </form>
    '''

# 检测参数是否为空
def valid_params(param, param1):
    if param==None or param1==None:
        return True
    return False



@app.route('/face_distance', methods=['GET','POST'])
def get_face_distance():
    if request.method == 'POST':
        encoding_1st=request.form.get('encoding_1st',type=str,default=None)
        encoding_2nd=request.form.get('encoding_2nd',type=str,default=None)
        if valid_params(encoding_1st,encoding_2nd):
            result = {
                "code": 200,
                "messages": "params error! Invalid encoding_1st/encoding_2nd"
            }
            return jsonify(result)
        else:
            face_encodings=[np.array(list(eval(encoding_1st)))]
            face_to_compare=np.array(list(eval(encoding_2nd)))
            face_distance=face_recognition.face_distance(face_encodings,face_to_compare)
            result={
                "code":200,
                "face_distance":face_distance.tolist()
            }
            return jsonify(result)



if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8086, debug=False)
